package sample;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import javafx.scene.web.WebEngine;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.Buffer;

/**
 * Register a protocol handler for URLs like this: <code>myapp:///pics/sland.gif</code><br>
 */
public class MyURLConnection extends URLConnection {

    private byte[] data = null;
    public String imgPath = "";

    /**
     * Constructs a URL connection to the specified URL. A connection to
     * the object referenced by the URL is not created.
     *
     * @param url the specified URL.
     */
    protected MyURLConnection(URL url) {
        super(url);
        System.out.println("URL: " + url);
    }

    @Override
    public void connect() throws IOException {
        if (connected) {
            return;
        }
        loadImage();
        connected = true;
    }

    @Override
    public String getHeaderField(String name) {
        if ("Content-Type".equalsIgnoreCase(name)) {
            return getContentType();
        } else if ("Content-Length".equalsIgnoreCase(name)) {
            return "" + getContentLength();
        }
        return null;
    }

    @Override
    public String getContentType() {
        // mime
        String ext = getURL().toString().substring(getURL().toString().lastIndexOf('.'));
        String mime = "text/" + ext.substring(1);
        System.out.println("MIME: " + mime);
        return mime; // TODO: switch based on file-type
    }

    @Override
    public int getContentLength() {
        return data.length;
    }

    @Override
    public long getContentLengthLong() {
        return data.length;
    }

    @Override
    public boolean getDoInput() {
        return true;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        System.out.println("getInputStream");
        return new ByteArrayInputStream(data);
    }

    public void loadImage() throws IOException {

        System.out.println("loadImage");
        int timeout = this.getConnectTimeout();
        long start = System.currentTimeMillis();
        URL url = getURL();

        imgPath = url.toExternalForm();
        imgPath = imgPath.startsWith("myapp:/") ? imgPath.substring("myapp:/".length()) : imgPath.substring("myapp:".length()); // attention: triple '/' is reduced to a single '/'

        System.out.println(imgPath);
        File file = new File(imgPath);
        loadhtml(file.getAbsolutePath());
    }

    public void loadhtml(String imgPath) {
        byte[] buf = new byte[1024];
        int n;
        FileInputStream fis = null;
        ByteOutputStream byteOutputStream = new ByteOutputStream();
        try {
            fis = new FileInputStream(imgPath);
            System.out.println(imgPath);

//此处可以通过debug模式查看，每次都读取1024个字节并通过write方法输出至控制台，最后一次读取buff往往不足1024个字节，实际上buff可以定义成任意长度，这样只是

//每次读取的字节数和读取次数不一样。
            int totalSize = 0;
            while ((n = fis.read(buf)) != -1) {
                byteOutputStream.write(buf, totalSize, n);
                totalSize += n;
//                System.out.write(data, 0, n);
            }
            data = byteOutputStream.getBytes();
            System.out.println(data);
        } catch (FileNotFoundException e) {
            System.out.println("没有找到文件");
            System.exit(1);
        } catch (IOException e) {
            System.out.println();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                System.out.println("文件错误");
                System.exit(1);
            }
        }
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        // this might be unnecessary - the whole method can probably be omitted for our purposes
        return new ByteArrayOutputStream();
    }

    @Override
    public java.security.Permission getPermission() throws IOException {
        return null; // we need no permissions to access this URL
    }

}